// function curry(fn) {
//     return function wrapFn(...args) {
//         if (args.length >= fn.length) {
//             return fn(...args)
//         }
//         else {
//             return function (...args1) {
//                 return wrapFn(...[...args, ...args1])
//             }
//         }
//     }
// }
// function add(a, b, c, d) {
//     return a + b + c + d;
// };

const mul = (x) => {
    let sum = x
    let curried = (y) => {
        sum = sum * y
        return curried
    }
    curried.valueOf = () => sum
    return curried
}

console.log(mul(1)) //1
console.log(mul(1)(2))//2
console.log(mul(1)(2)(3))//6
console.log(mul(1)(2)(3)(4))//24

// var newAdd = curry(add);
// console.log(newAdd(1)(2)(3)(4))
// console.log(newAdd(1, 2)(3, 4));
// console.log(newAdd(1, 2, 3)(4));


function compose(fns) {
    return function (data) {
        return fns.reduce((pre, next) => {
            return next(pre)
        }, data)
    }
}


const add = (x) => x * 1 + 10
const square = (z) => z * z
const test1 = () => square(add(1, 2))
console.log(test1()) // 9

// 如果希望从右向左执行
// fns可以反转一下啊 arr.reverse
console.log(compose([add, square])(1))



function curry(fn) {
    return function curried(...args) {
        if (fn.length === args.length) {
            return fn.call(this, ...args)
        } else {
            return function (...args1) {
                return curried(...[...args, ...args1])
            }
        }
    }
}

function compose(...fns) {
    return function (data) {
        return fns.reduce((pre, next) => {
            return next(pre)
        }, data)
    }
}

function debounce(fn, delay) {
    let timer = null;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.call(this, ...args)
        }, delay)
    }
}

function throttle(fn, delay) {
    let timer = null;
    return function (...args) {
        if (!timer) {
            fn.call(this, ...args)
            timer = setTimeout(() => {
                timer = null
            }, delay)
        }
    }
}


Promise.prototype.myAll = function (fns) {
    let result = []
    return new Promise((resolve, rejected) => {
        for (let i = 0; i < fns.length; i++) {
            fns[i]().then(res => {
                result[i] = res
                if (fns.length === result.length) {
                    resolve(result)
                }
            }).catch(err => {
                rejected(err)
            })
        }
    })
}